package com.imagination.applet.infrastructure.utils;

import com.google.common.collect.Maps;
import com.imagination.applet.controller.web.configuration.JwtToken;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;


public class JwtUtils {
    private static final String secretKey = "WlcgIA073rBZjT5SLuR08q4HkBATwkMF/uU/q9j0F9w=";

    private static final Key key = Keys.hmacShaKeyFor(secretKey.getBytes());

    public static String createToken(String id, String subject, Map<String, Object> claims, Long expirationTime) {
        return Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .addClaims(claims)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expirationTime))
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    public static void main(String[] args) {
        System.out.println(1111);
        Map<String, Object> claims = Maps.newHashMap();
        claims.put(JwtToken.USER_ID, "10000001");
        claims.put(JwtToken.OPEN_ID, "4");
        claims.put(JwtToken.OPEN_ID_TYPE, "5");
        claims.put(JwtToken.ACCESS_KEY, "6");
        String token = createToken("1", "2", claims, 30*24*3600*1000L);
        System.out.println(token);
    }

    public static Long exactUserId(String token) {
        Jws<Claims> jws = parse(token);
        return Long.valueOf(jws.getBody().get("userId").toString());
    }

    public static String exactAccessKey(String token) {
        Jws<Claims> jws = parse(token);
        return jws.getBody().get("accessKey").toString();
    }

    public static Jws<Claims> parse(String token) {
        return (Jws<Claims>) Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token);

    }
}
